package com.yeshine.opendata.service.impl;

import com.yeshine.opendata.core.AppException;
import com.yeshine.opendata.core.ControllerBase;
import com.yeshine.opendata.core.ServiceBase;
import com.yeshine.opendata.dao.IDataDao;
import com.yeshine.opendata.entity.Data;
import com.yeshine.opendata.entity.SysDictionary;
import com.yeshine.opendata.service.IDataService;
import com.yeshine.opendata.service.IDataSetService;
import com.yeshine.opendata.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by taohj on 2014/7/14.
 */
@Service
public class DataServiceImpl extends ServiceBase<Data> implements IDataService {


    private IDataDao dao;

    private IDataSetService dataSetService;


    @Autowired
    public void setDao(IDataDao dao) {
        this.dao = dao;
    }

    @Autowired
    public void setDataSetService(IDataSetService dataSetService) {
        this.dataSetService = dataSetService;
    }

    private final String path = UploadConstantPath.DATA_FILE_PATH;


    @Override
    public Result<Data> create(Data data) {
        data.setCreateTime(new Date());
        data.setStatus(new SysDictionary(111));
        data.setVersion(data.getVersion() + "_" + System.currentTimeMillis());
        data.setAuditStatus(new SysDictionary(181));
       /*  SearchEngine searchEngine = new SearchEngine();
        searchEngine.IndexData(data);*/
        if (dao.insert(data) <= 0) {
            return new Result<Data>(false, "数据新增失败");
        } else {
            return new Result<Data>(true);
        }
    }

    @Override
    public Result<Data> remove(Data data) {
        data = this.getById(data.getId()).getTarget();
        if (data.getStorage() != null && data.getStorage().getId() != null && data.getStorage().getId() == 131 && StringUtils.hasLength(data.getUrl())) {
            String realpath = ControllerBase.getRequest().getSession().getServletContext().getRealPath(data.getUrl());
            File file = new File(realpath);
            File parent = file.getParentFile();
            try {
                org.apache.commons.io.FileUtils.deleteDirectory(parent);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new Result<Data>(dao.delete(data) > 0);
    }


    @Override
    public Result<Data> modify(Data data) {

        data.setUpdateTime(new Date());

        if (StringUtils.hasLength(data.getVersion())) {
            if (data.getVersion().lastIndexOf("_") >= 0) {
                data.setVersion(data.getVersion().substring(0, data.getVersion().lastIndexOf("_")) + "_" + System.currentTimeMillis());
            } else {
                data.setVersion(data.getVersion() + "_" + System.currentTimeMillis());
            }
        }
        if (dao.update(data) <= 0) {
            return new Result<Data>(false, "数据更新失败");
        }
        return new Result<Data>(true);
    }


    @Override
    public Result<Data> getById(Integer id) {
        return new Result<Data>(dao.selectById(id));
    }

    @Override
    public Result<Data> getList(Data data) {
        return new Result<Data>(dao.selectList(data));
    }

    @Override
    public Result<Data> getByPage(PageResult<Data> pageResult) {
        pageResult.setRows(dao.selectbyPage(pageResult));
        return new Result<Data>(pageResult);
    }

    @Override
    public Result<Data> create(Data data, HttpServletRequest request) {


        if (!this.create(data,request).isSuccess()) {
            return new Result<Data>(false, "新增数据失败");
        }
        String path = request.getSession().getServletContext().getRealPath(this.path) + "/" + data.getId() + "/";
        String url = this.path + data.getId() + "/";
        String fileName = null;

        MultipartFile file = data.getFile();

        if (data.getStorage() != null && data.getStorage().getId() != null && data.getStorage().getId() == 131 && file != null && file.getSize() > 0) {

            fileName = file.getOriginalFilename();
            url += fileName;

            data.setUrl(url);
            File targetFile = new File(path, fileName);
            try {
                FileUtils.copy(file.getInputStream(), targetFile);
                OfficeExtractor.toHtml(path + fileName, path + fileName.substring(0, fileName.lastIndexOf(".")) + ".html");
                data.setUrl(url);
            } catch (IOException e) {
                e.printStackTrace();
                return new Result<Data>(false, e.getMessage());
            }
            data.setFileFormat(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1));
        }
        return this.modify(data);
    }

    @Override
    public Result<Data> modify(Data data, HttpServletRequest request) {


        //开始修改
        String path = request.getSession().getServletContext().getRealPath(this.path) + "/" + data.getId() + "/";
        String url = this.path + data.getId() + "/";
        String fileName;
        MultipartFile file = data.getFile();


        if (data.getStorage() == null || data.getStorage().getId() == null) {
            Data d = this.getById(data.getId()).getTarget();
            data.setUrl(d.getUrl());
        } else if (data.getStorage().getId() == 131 && file != null && file.getSize() > 0) {


            //删除文件及文件夹
            Data olddata = this.getById(data.getId()).getTarget();
            if (olddata.getStorage() != null && olddata.getStorage().getId() != null && olddata.getStorage().getId() == 131 && StringUtils.hasLength(olddata.getUrl())) {
                String realpath = ControllerBase.getRequest().getSession().getServletContext().getRealPath(olddata.getUrl());
                try {
                    org.apache.commons.io.FileUtils.deleteDirectory(new File(realpath).getParentFile());
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new AppException(e.getMessage());
                }
            }





            //开始文件拷贝
            fileName = file.getOriginalFilename();
            url += fileName;
            File targetFile = new File(path, fileName);
            try {
                FileUtils.copy(file.getInputStream(), targetFile);
                OfficeExtractor.toHtml(path + fileName, path + fileName.substring(0, fileName.lastIndexOf(".")) + ".html");
                data.setUrl(url);
            } catch (IOException e) {
                e.printStackTrace();
                return new Result<Data>(false, e.getMessage());
            }
            data.setFileFormat(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1));

        }
        return this.modify(data);
    }

   /* @Override
    public Result<Data> search(PageResult<Data> pageResult) {
        SearchEngine searchEngine = new SearchEngine();
        List<Data> list = searchEngine.SearchData(pageResult.getKeyWord());
        int page = pageResult.getPage() != null || pageResult.getPage() < 1 ? pageResult.getPage() : 1;
        int size = pageResult.getSize() != null || pageResult.getSize() < 10 ? pageResult.getSize() : 10;
        int startIndex = page < 1 ? 1 : (page - 1) * size;
        int endIndex = page < 1 ? page * size + size : page * size;
        List<Data> returnList = new ArrayList<Data>();
        if (list == null || list.size() == 0) {
            pageResult.setTotal(0);
            pageResult.setRows(returnList);
            return new Result<Data>(pageResult);
        }
        for (int i = startIndex; i < endIndex && i < list.size(); i++) {
            returnList.add(list.get(i));
        }

        pageResult.setPage(page);
        pageResult.setSize(size);
        pageResult.setRows(returnList);
        pageResult.setTotal(list.size());
        return new Result<Data>(pageResult);
    }*/


    @Override
    public Result<Data> search(PageResult<Data> pageResult) {

        return this.getByPage(pageResult);
    }

    @Override
    public List<String> getGroupByFormat(Data data) {
        return dao.selectGroupByFormat(data);
    }

    @Override
    public List<String> getGroupByTags(Data data) {
        return dao.selectGroupByTags(data);
    }

    @Override
    public List<String> getGroupByLicense(Data data) {
        return dao.selectGroupByLicense(data);
    }

    @Override
    public List<String> getTopTags(Data data) {
        return dao.selectTopTags(data);
    }


    @Override
    public Result<Data> audit(Integer auditStatus, Integer[] datas) {
        Result<Data> result = null;
        if (dao.audit(auditStatus, datas) > 0) {
            result = new Result<Data>(true, "审批成功");
        } else {
            result = new Result<Data>(false, "审批失败,请联系管理员");
        }
        return result;
    }


}
